// ==UserScript==
// @name         xsstudy学习脚本
// @namespace    http://tampermonkey.net/
// @version      0.8
// @description  try to take over the world!
// @author       CPLex
// @match        http://www.xsstudy.gov.cn/nbstudy/*
// @grant        none
// @require     https://code.jquery.com/jquery-latest.js
// ==/UserScript==
/* 更新日志
  v0.1 首版
  v0.2 加入进度显示（百分比）优化代码
  v0.3 进度条显示优化
  v0.4 利用localstrage 储存进度数据
  v0.5 测试自动学习
  v0.6 代码优化,自动学习仍然出错
  v0.7 添加清除本地储存按钮, 暂时移除自动学习功能
  v0.8 加入自动学习功能
*/
(function() {

    function Lesson(id, node) {
        this.id = id;
        this.node = node;
        this.title = getCourseTitle(id); //题目
        this.duration = parseInt(getCourseRlen(id)); //时长（分钟
        this.lastTime = 0;
        this.isLearning = 0; //是否正在学习(否)  用this.isLearning^1表示学习状态，返回true表示播放，否则暂停
        var webLastTime = getsTime(id) * 60; //网页显示的已获学时（分钟）
        var localLastTime = parseInt(localStorage.getItem("lastTime" + id)); // 本地储存的已获学时（分钟）
        //比较网页显示与本地储存的学时,将较大值用this.lastTime变量表示
        //如果本地储存不为空,且本地学时 > 网页学时,则显示本地学时
        if (localLastTime && (localLastTime >= webLastTime)) {
            this.lastTime = localLastTime;
        } else {
            this.lastTime = webLastTime;
        }
        localStorage.setItem("lastTime" + id, this.lastTime); //将已获学时储存在本地
        //进度条设定
        this.progress = document.createElement('td');
        if (this.duration > 0) {
            this.progress.innerHTML = (this.lastTime / this.duration * 100).toFixed(2) + "%";
        } else {
            this.progress.innerHTML = '<td>0.00%</td>';
        }
        this.progress.id = "pro" + this.id;
        this.node.appendChild(this.progress);
        //播放按钮设定
        this.playButton = document.createElement('td');
        this.node.appendChild(this.playButton);
        this.playButton.innerHTML = "<button>▶</button>";
        this.playButton.id = "button" + this.id;
        this.playButton.onclick = function() {
                //如果正在自动学习
            if (document.getElementById("checkbox_auto").checked){
                alert("请取消自动学习后再进行操作");
            } else {
                //如果本课程在学习中，点击则暂停学习
                if (this.isLearning) {
                    this.pause();
                } else {
                    //如果其他课程在学习，暂停其他课程
                    if (Lesson.currentLesson !== null) {
                        Lesson.currentLesson.pause();
                    }
                    //开始学习本课程
                    this.start();
                }
            }
        }.bind(this);
    }
    //当前课程
    Lesson.currentLesson = null;
    Lesson.intervalID = 0;
    //开始学习
    Lesson.prototype.start = function() {
        this.isLearning = this.isLearning ^ 1;
        Lesson.currentLesson = this;
        this.playButton.innerHTML = "<button>||</button>";
        Lesson.intervalID = setInterval(function() {
            $.ajax({
                type: "POST",
                url: '/nbstudy/player.ww?rid=0&cid=' + this.id + '&classid=WX&lastPlayTime=0&' + Math.round(Math.random() * 999999999),
                data: '',
                success: function(msg) {
                    if (msg.indexOf("success") < 0) {
                        console.log("课程" + this.id + "计时错误,请稍后(1小时)再学");
                    } else {
                        this.lastTime ++;
                        this.progress.innerHTML = ((this.lastTime / this.duration) * 100).toFixed(2) + "%";
                        localStorage.setItem("lastTime" + this.id, this.lastTime);
                        console.log("正在学习课程ID号" + this.id);
                        console.log("已持续" + this.lastTime + "分钟");
                        console.log("总时长" + this.duration + "分钟");
                    }
                }.bind(this)
            });
        }.bind(this), 60000);
    };
    //暂停学习
    Lesson.prototype.pause = function() {
        this.isLearning = this.isLearning ^ 1;
        this.playButton.innerHTML = "<button>▶</button>";
        clearInterval(Lesson.intervalID);
        Lesson.currentLesson = null;
    };
    //是否有效
    Lesson.prototype.isValid = function() {
        return this.duration > 0;
    };
    //是否已完成
    Lesson.prototype.isFinished = function() {
        //console.log("课程" + this.id + "已完成");
        return this.lastTime >= this.duration;
    };

    function LessonManger(lessons) {
        this.lessons = lessons;
        this.cursor = 0; //ToDO: 优化getLesson()方法
        this.checkIntervalID = 0;
    }

    LessonManger.prototype.getLesson = function() {
        for (var i = 0; i < this.lessons.length; i++) {
            if (this.lessons[i].isValid() && (!this.lessons[i].isFinished())) {
                console.log("获取新课程" + this.lessons[i].id);
                return this.lessons[i];
            }
        }
        return undefined;
    };

    LessonManger.prototype.startCheck = function() {
        var firstLesson = this.getLesson();
        //如果没有课程在学习,且本页仍有未学习课程
        if (firstLesson) {
            if (!Lesson.currentLesson) {
                firstLesson.start();
            }
            this.checkIntervalID = setInterval(function() {
                if (Lesson.currentLesson.isFinished()) {
                    var newLesson = this.getLesson();
                    if (newLesson) {
                        Lesson.currentLesson.pause();
                        newLesson.start();
                    } else {
                        Lesson.currentLesson.pause();
                        this.stopCheck();
                        alert("本页课程均已学完");
                    }
                }
            }.bind(this), 60000);
        } else {
            alert("本页课程均已学完");
        }

    };
    LessonManger.prototype.stopCheck = function() {
        clearInterval(this.checkIntervalID);
    };
    LessonManger.prototype.setAutoStudy = function() {
        autoButton = document.createElement("input");
        autoButton.type = "checkbox";
        autoButton.value = "0";
        autoButton.id = "checkbox_auto";
        autoLable = document.createTextNode("自动学习");
        $(":submit")[0].parentNode.appendChild(autoButton);
        $(":submit")[0].parentNode.appendChild(autoLable);
        autoButton.onclick = function() {
            if (autoButton.checked) {
                console.log("开始自动学习");
                this.startCheck();
            } else {
                console.log("停止自动学习");
                this.stopCheck();
            }
        }.bind(this);
    };

    function CleanLocalStorage() {
        cleanButton = document.createElement("input");
        cleanButton.type = "button";
        cleanButton.value = "清除本地储存";
        cleanButton.id = "button_clean";
        $(":submit")[0].parentNode.appendChild(cleanButton);
        cleanButton.onclick = function() {
            localStorage.clear();
            alert("本地储存已清除，请刷新页面查看效果");
        };
    }

    function main() {
        var a = $('[id^=js_exetend]');
        var lesson = [];
        for (var i = 0; i < a.length; i++) {
            var node = a[i].parentNode.parentNode.parentNode;
            var classId = a[i].id.slice(11);
            lesson[i] = new Lesson(classId, node);
        }
        CleanLocalStorage();
        manager = new LessonManger(lesson);
        manager.setAutoStudy();
    }
    main();

})();